package com.medium.house.utils.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Slf4j
public class HttpRequest {

	private static final String CHARSET = "UTF-8";

	private static CloseableHttpClient httpclient;

	static {
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(100);
		cm.setDefaultMaxPerRoute(100);
		httpclient = HttpClients.custom().setConnectionManager(cm).build();
	}

	public static String post(String url, String data) {
		HttpPost httppost = new HttpPost(url);
		// 配置请求的超时设置,连接建立超时时间10s，响应超时时间20s，从连接池获取连接的超时时间10s
		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000)
				.setConnectTimeout(10 * 1000).setSocketTimeout(20 * 1000).build();
		httppost.setConfig(requestConfig);
		CloseableHttpResponse httpReponse = null;
		try {
			httppost.setEntity(new StringEntity(data, "utf-8"));
			httppost.addHeader("Content-Type", "application/json;charset=utf-8");
			httppost.addHeader("accept-type", "utf-8");

			log.info("HttpRequest post execute start. [parameter = {}]", data);

			httpReponse = httpclient.execute(httppost);
			int status = httpReponse.getStatusLine().getStatusCode();
			if (status == 200) {
				HttpEntity entity = (HttpEntity) httpReponse.getEntity();
				String result = EntityUtils.toString(entity, CHARSET);
				if (StringUtils.isEmpty(result)) {
					log.warn("HttpRequest post execute end result is null. [parameter = {}]", data);
				} else {
					log.info("HttpRequest post execute end. [parameter = {} , result = {}]", data, result);
					return result;
				}
			} else {
				log.warn("HttpRequest post status error. [status ={}]", status);
			}
		} catch (ParseException e) {
			log.error("HttpRequest post parse exception.", e);
		} catch (IOException e) {
			log.error("HttpRequest post I/O exception.", e);
		} finally {
			if (httpReponse != null) {
				try {
					httpReponse.close();
				} catch (IOException e) {
					log.error("HttpRequest post close exception.", e);
				}
			}
		}
		return "";
	}

	public static String get(String url) {
		HttpGet httpGet = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000)
				.setConnectTimeout(10 * 1000).setSocketTimeout(20 * 1000).build();
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse httpReponse = null;
		try {
			httpReponse = httpclient.execute(httpGet);
			int status = httpReponse.getStatusLine().getStatusCode();
			if (status == 200) {
				HttpEntity entity = (HttpEntity) httpReponse.getEntity();
				String result = EntityUtils.toString(entity, CHARSET);
				log.info("HttpRequest get execute end. [result = {}]", result);
				return result;
			} else {
				log.warn("HttpRequest get status error. [status ={}]", status);
			}
		} catch (Exception e) {
			log.error("HttpRequest get error", e);
		}
		return "";
	}
	
	public static String callMopayGatewayOrderQuery(String url,Map<String, String> parameter,String charSet) {
		HttpPost httppost = new HttpPost(url);
		// 配置请求的超时设置,连接建立超时时间10s，响应超时时间20s，从连接池获取连接的超时时间10s
		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000)
				.setConnectTimeout(10 * 1000).setSocketTimeout(20 * 1000).build();
		httppost.setConfig(requestConfig);
		CloseableHttpResponse httpReponse = null;
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for(String key:parameter.keySet()){
				params.add(new BasicNameValuePair(key, parameter.get(key)));
			}
		    
			httppost.setEntity(new UrlEncodedFormEntity(params,charSet));
			httppost.addHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charSet);

			log.info("HttpRequest callMopayGatewayOrderQuery execute start. [parameter = {}]", parameter);
			
			httpReponse = httpclient.execute(httppost);
			int status = httpReponse.getStatusLine().getStatusCode();
			if (status == 200) {
				HttpEntity entity = (HttpEntity) httpReponse.getEntity();
				String result = EntityUtils.toString(entity, charSet);
				if (StringUtils.isEmpty(result)) {
					log.warn("HttpRequest callMopayGatewayOrderQuery execute end result is null. [parameter = {}]", parameter);
				} else {
					log.info("HttpRequest callMopayGatewayOrderQuery execute end. [parameter = {} , result = {}]", parameter, result);
					return result;
				}
			} else {
				log.warn("HttpRequest callMopayGatewayOrderQuery status error. [status ={}]", status);
			}
		} catch (ParseException e) {
			log.error("HttpRequest callMopayGatewayOrderQuery parse exception.", e);
		} catch (IOException e) {
			log.error("HttpRequest callMopayGatewayOrderQuery I/O exception.", e);
		} finally {
			if (httpReponse != null) {
				try {
					httpReponse.close();
				} catch (IOException e) {
					log.error("HttpRequest callMopayGatewayOrderQuery close exception.", e);
				}
			}
		}
		return "";
	}

}
